// 创建元素并设置属性、class、子节点
export function createElement<K extends keyof HTMLElementTagNameMap>(
    tag: K,
    options: {
        className?: string;
        attrs?: Record<string, string>;
        children?: (HTMLElement | Text)[];
    } = {}
): HTMLElementTagNameMap[K] {
    const el = document.createElement(tag);
    if (options.className) el.className = options.className;
    if (options.attrs) {
        for (const [k, v] of Object.entries(options.attrs)) {
            el.setAttribute(k, v);
        }
    }
    if (options.children) {
        options.children.forEach(child => el.appendChild(child));
    }
    return el;
}

export function addClass(el: Element, className: string) {
    el.classList.add(className);
}

export function removeClass(el: Element, className: string) {
    el.classList.remove(className);
}

export function toggleClass(el: Element, className: string) {
    el.classList.toggle(className);
}

export function createId(prefix: string = "id") {
    return `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1000000)}`;
}

/**
 * 获取当前页面的域名
 * 如：https://www.example.com/path/page.html
 * 则返回 www.example.com
 * @returns 域名
 */
export function getDomain() {
    const url = window.location.href;
    return url.replace(/https?:\/\/|\/.*$/g, "");
}